<template>
  <!-- STEP1：在HTML中添加包裹容器元素 -->
  <div style=" display: flex;align-items: center;margin-top: 15%;justify-content: center;">
    <div id="self_defined_element" class="self-defined-classname"></div>
<!--    {{'url: '+url}}-->
<!--    {{'errMsg: '+key}}-->
<!--    {{'code:'+JSON.stringify(code)}}-->
<!--    {{'step:' + step}}-->
<!--    {{'auth:' + JSON.stringify(authConfig)}}-->
<!--    {{'userInfo:' + JSON.stringify(elm.info)}}-->
  </div>
</template>


<script>
  import * as dd from 'dingtalk-jsapi';
export default {
  extends: elmVueBase,
  name: "CustomFieldForm",
  data() {
    return {
    //  error: '',
      code: '',
      step: 0,
      authConfig: {},
      userInfo: {},
      url: '',
      key:''
      // ...
    }
  },
  props: {
    // ...
    logo: {
      type: String,
      default: 'sn'
    }
  },
  watch: {
    logo: function (oldVal, newVal) {
      console.log(111111111111)
      debugger
     // this.key = newVal
      this.login(newVal)
    }
    // ...
  },
  mounted() {
    this.login(this.logo)
  },
  methods:{
  async login(val) {
    try{
      this.step = 1
      debugger
      console.log('logo:' + val)
      if (elm.info.user) {
        this.step = 2.5
        this.userInfo = elm.info.user;
        location.href = elm.settings.routefix + elm.info.system.path;
        return
      }
      this.key = val

      let authConfig = await elm.post("/system/login/dingtalk/authConfig?key="+val,{})

      this.authConfig = authConfig
      if (authConfig) {
        this.step = 2
        // 常见错误：未正确初始化
        this.step = 3
        dd.config({
          appId:authConfig['agent_id'],
          corpId:authConfig['corp_id'],
          timeStamp: new Date().getTime(),
          nonceStr:authConfig['nonceStr'],
          signature:authConfig['signature'],
          jsApiList:['biz.contact.choose',],
        });
        this.step= 3.5
        this.$nextTick(()=>{
          // console.log('key: '+this.key)
          this.url = JSON.stringify(elm.info);
          this.step = 3.7
          dd.ready( () =>{
            this.step= 3.6


            this.step = 4
            dd.requestAuthCode({
              corpId: authConfig['corp_id'],
              clientId: authConfig['client_id'],
              onSuccess : async (result) =>{
                this.step = 5
                this.code = result;

                try{
                  let res = await elm.post("/system/login/dingtalk/auth?authCode=" + result.code + '&key=' + val, {})
                  this.userInfo=JSON.stringify(res)
                  this.step = 6
                  if (res.success == true) {
                    this.step = 7
                    elm.info.token = res.token;
                    // const parts = this.model.id.split(".");
                    elm.info.tenant =this.key;

                    this.step = 11
                    elm.info.system = res.system;
                    elm.info.menu = res.menu;
                    elm.info.user = res.user;
                    elm.info.org = res.org;
                    elm.info.role = res.role;
                    location.href = elm.settings.routefix + elm.info.system.path;
                    //记录日志
                    let oper_log = {};
                    oper_log.oper_type = "2"; //钉钉
                    oper_log.user_name = res.user.name;
                    oper_log.nick_name = res.user.name;
                    oper_log.menu_title = "/system/login/dingtalk/auth";
                    oper_log.oper_time = new Date().toLocaleString();
                    oper_log.msg = "登录";
                    await elm.post('/system/login/log/Upsert', oper_log);
                  } else if (res.success == false || res.status == 401) {
                    this.model.msg = "用户名或密码错误。";
                    // top.location.href = elm.settings.routefix+elm.settings.loginPath;
                  } else {
                    this.model.msg = "登录失败，请稍后重试。";
                    // top.location.href = elm.settings.routefix+elm.settings.loginPath;
                  }
                } catch (e) {
                  alert('login error: ' ,e);
                }
              },
              onFail:  (err)=> {
                window.DTFrameLogin(
                    {
                      id: 'self_defined_element',
                      width: 300,
                      height: 300,
                    },
                    {
                      redirect_uri: encodeURIComponent('http://127.0.0.1:8120/system/login/dingtalk/auth'),
                      client_id: authConfig['client_id'],
                      scope: 'openid',
                      response_type: 'code',
                      state: 'xxxxxxxxx',
                      prompt: 'consent',
                    },
                    (loginResult) => {
                      const {redirectUrl, authCode, state} = loginResult;
                      // 这里可以直接进行重定向
                      window.location.href = redirectUrl;
                      // 也可以在不跳转页面的情况下，使用code进行授权
                      console.log(authCode);
                    },
                    (errorMsg) => {
                      // 这里一般需要展示登录失败的具体原因,可以使用toast等轻提示
                    //  console.error(`errorMsg of errorCbk: ${errorMsg}`);
                    },
                );
              },
            });
          });
          dd.error((err) => {
            alert('dd error: ' + JSON.stringify(err));
          })
        })

        //this.step=999

      }

    } catch (e) {
     // this.error = e.message
    }
  }
  }

}
// STEP3：在需要的时候，调用 window.DTFrameLogin 方法构造登录二维码，并处理登录成功或失败的回调。

</script>
<style>
/* STEP2：指定这个包裹容器元素的CSS样式，尤其注意宽高的设置 */
.self-defined-classname {
  display: flex;
  align-items: center;
  width: 300px;
  height: 300px;
}
</style>